<?php 
class ShopExe
{
	function getShopCatsMenuHTML($cats)
	{
		if($cats)
		{
			$output .= '<ul>';
			foreach($cats as $cat)
			{

				$style = ' style="background-image:url('.SYSICONS_URL.'treemenu/folder_tar_16.gif)" ';
				$output .= '<li id="cat_'.$cat['id'].'" class="'.$li_class.' leaf" '.$state.' rel="product_cat">';
				$output .= '<a '.$style.' href="?con='.$_REQUEST['con'].'&amp;cat='.$cat['id'].'">';
				$output .= $cat['title'];
				$output .= '</a>';
				$output .= '</li>';
			}
			$output .= '</ul>';
		}
		return $output;
	}
	
	function getShopExe($id=0)
	{
		
		if($id > 0)
		{ $select = 'SELECT * FROM '.DB_PERFIX.'shop_exe WHERE id='.$id.';'; }
		else
		{ $select = 'SELECT * FROM '.DB_PERFIX.'shop_exe;'; }
		
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			$i=0;
			while($row = mysql_fetch_array($result))
			{
				if($id > 0)
				{
					foreach(array_keys($row) as $key)
					{ $item[$key] = $row[$key]; }
				}
				else
				{
					foreach(array_keys($row) as $key)
					{ $item[$i][$key] = $row[$key]; }
					$i++;
				}
			}
			return $item;
		}
	}
	
	function addShopExe($title, $type=0)
	{
		if($title != '')
		{
			$insert  = 'INSERT INTO '.DB_PERFIX.'shop_exe (`title`, `type`)'; 
			$insert .= 'VALUES ("'.$title.'", '.$type.');';
			$result = mysql_query($insert);
			if ($result > 0)
			{
				$result = mysql_query("SELECT id FROM ".DB_PERFIX."shop_exe WHERE title LIKE '".$title."' ORDER BY id DESC LIMIT 1;");
				while($row = mysql_fetch_array($result))
				{
					$item['id'] = $row['id'];
					$item['title'] = $name;
					$item['type'] = $type;
				}
			}
			return $item;
		}
	}
	
	function saveShopExe($id, $title, $type=0, $frequency=0, $timeset=0, $source='')
	{	
		if($id > 0)
		{
			if(!($timeset > -1))
			{ $timeset = 0; }
			if(!($frequency > -1))
			{ $frequency = 0; }
			$source = substr($source, 0, 400);
			
			$update  = 'UPDATE '.DB_PERFIX.'shop_exe SET ';
			$update .= 'title="'.$title.'", ';
			$update .= 'type='.$type.', ';
			$update .= 'frequency='.$frequency.', ';
			$update .= 'timeset='.$timeset.' ';
			$update .= 'WHERE id='.$id.' LIMIT 1;';
			$update = mysql_query($update);
		}
	}
	
	function saveShopExeSource($id, $src_type=0, $src_loc_type=0, $src_loc='')
	{	
		if($id > 0)
		{
			$update  = 'UPDATE '.DB_PERFIX.'shop_exe SET ';
			$update .= 'src_type='.$src_type.', ';
			$update .= 'src_loc_type='.$src_loc_type.', ';
			$update .= 'src_loc="'.$src_loc.'" ';
			$update .= 'WHERE id='.$id.' LIMIT 1;';
			$update = mysql_query($update);
		}
	}
	
	function saveShopExeSourceContent($id, $content='')
	{	
		if($id > 0)
		{ 
			$filename = $id.'_'.date('Y-m-d-H-i-s').'.csv';
			$path = PRODUCT_PATH.'import/csv/';
			file_put_contents($path.$filename, $content); 
			if(is_file($path.$filename))
			{
				$update  = 'UPDATE '.DB_PERFIX.'shop_exe SET ';
				$update .= 'src_loc_type=1, ';
				$update .= 'src_loc="'.$filename.'" ';
				$update .= 'WHERE id='.$id.' LIMIT 1;';
				$update = mysql_query($update);
			}
		}
	}
	
	function saveShopExeFormat($id, $delimiter=';', $def_row=1, $start_row=1, $target_root_id=0)
	{	
		if($id > 0)
		{
			$update  = 'UPDATE '.DB_PERFIX.'shop_exe SET ';
			$update .= 'delimiter="'.$delimiter.'", ';
			$update .= 'target_root_id='.$target_root_id.', ';
			$update .= 'def_row='.$def_row.', ';
			$update .= 'start_row='.$start_row.' ';
			$update .= 'WHERE id='.$id.' LIMIT 1;';
			$update = mysql_query($update);
		}
	}
	
	function deleteShopExe($id)
	{	
		if($id > 0)
		{
			$delete = 'DELETE FROM '.DB_PERFIX.'shop_exe_fields WHERE parent_id='.$id.';';
			$result = mysql_query($delete);
			
			$delete = 'DELETE FROM '.DB_PERFIX.'shop_exe WHERE id='.$id.' LIMIT 1;';
			$result = mysql_query($delete);
			return ;
		}
	}
	
	function runImport($exe, &$eFields, &$cats, &$groups, &$providers, &$brands, &$attributes, $siteAdmin, $shopCom, $shopCat, $shopProv, $ShopAtt)
	{	
		if($exe)
		{	
			if(is_file(PRODUCT_PATH.'import/csv/'.$exe['src_loc']))
			{
				$columns = 0;
				$row = 1;
				$output = '';
				$lines = count(file(PRODUCT_PATH.'import/csv/'.$exe['src_loc']));
				$handle = fopen(PRODUCT_PATH.'import/csv/'.$exe['src_loc'], "r");
				if($handle)
				{ 
					while (($data = fgetcsv($handle, 1000, $exe['delimiter'])) !== FALSE)
					{ 
						//if(($row > 0) && ($row < 6))
						if($row > 0)
						{ 
							if($row == $exe['def_row'])
							{ 
								$output .= self::runImportRow($exe, $data, $eFields, $cats, $groups, $providers, $brands, $attributes, $shopCom, $siteAdmin, $shopCat, $shopProv, $ShopAtt, true);  
								$ShopExeImpField = new ShopExeImpField();
								$eFields = $ShopExeImpField->getFields($exe['id']);
							}
							else
							{ 
								$output .= self::runImportRow($exe, $data, $eFields, $cats, $groups, $providers, $brands, $attributes, $shopCom, $siteAdmin, $shopCat, $shopProv, $ShopAtt, false); 
							}
						}
						$row++; 
					}
					fclose($handle);
				}
				return $output;
			}
		}
	}
	
	function runImportRow($exe, $row, &$eFields, &$cats, &$groups, &$providers, &$brands, &$attributes, $shopCom, $siteAdmin, $shopCat, $shopProv, $ShopAtt, $d)
	{
		if(($exe) && ($eFields) && ($row))
		{
			$i = 1;
			$j = 0;
			$exit = 0;
			$title = '';
			$output = '';
			
			if($d)
			{ $output .= 'Running Definitions Row<br />'; }
			
			if($exe['target_root_id'] > 0)
			{ $root = $exe['target_root_id']; }
			
			foreach($eFields as $field)
			{
				// Make Product Attributes
				if($d) //Definitions Row
				{
					if($field['to_table'] == 'product_vals')
					{
						if($row[$field['from_field_no']] != '')
						{
							if($field['to_field'] == -1) // Not defined attribute
							{
								$aid = 0;
								$aid = $ShopAtt->findCreateAttribute($attributes, $row[$field['from_field_no']], $ShopAtt);
								$output .= 'Found/Created Attribute'.$row[$field['from_field_no']].'<br />';
								if($aid > 0)
								{ 
									$update = 'UPDATE '.DB_PERFIX.'shop_exe_fields SET to_field='.$aid.' WHERE id='.$field['id'].';';
									$result = mysql_query($update);
									$field['to_field'] = $aid; 
								}
							}
						}
					}
				}
				else
				{
					if(($row[$field['if_empty_action']] == 1) && ($row[$field['from_field_no']] = ''))
					{ return; }
					
					if(($field['to_field'] != 'active_start') && ($field['to_field'] != 'active_end'))
					{
						if(($row[$field['from_field_no']] == '') && ($field['if_empty_action'] == 2))
						{ $row[$field['from_field_no']] = $field['default_value']; }
					}
					if($row[$field['from_field_no']] != '')
					{ $row[$field['from_field_no']] = trim($field['perfix'].$row[$field['from_field_no']].$field['postfix']); }
					
					// Make title string
					if(($field['to_table'] == 'product') && ($field['to_field'] == 'title'))
					{ $title = $row[$field['from_field_no']]; }
					
					// Make Identity String
					if(($field['to_table'] == 'product_vars') && ($field['to_field'] == 'identity'))
					{ $identity[0] = $row[$field['from_field_no']]; }
					if(($field['to_table'] == 'product_vars') && ($field['to_field'] == 'identity_1'))
					{ $identity[1] = $row[$field['from_field_no']]; }
					if(($field['to_table'] == 'product_vars') && ($field['to_field'] == 'identity_2'))
					{ $identity[2] = $row[$field['from_field_no']]; }
					if(($field['to_table'] == 'product_vars') && ($field['to_field'] == 'identity_3'))
					{ $identity[3] = $row[$field['from_field_no']]; }
					
					// Make Section String
					if($field['to_table'] == 'menu')
					{ 
						if(trim($row[$field['from_field_no']]) != '')
						{ $sections[$field['to_field']] .= $row[$field['from_field_no']]; }
					}
				}
			}
			
			if(($identity) && ($d == false))
			{
				$operation = 0;
				$parent	= 0;
				
				$identity[0] = $identity[0].$identity[1].$identity[2].$identity[3];
				
				if($title == '')
				{ $title = $identity[0]; }
				
				$product = $shopCom->getProduct(0, $identity[0]);
				
				if((!($product)) || (!($product['id'] > 0)))
				{ 
					$output .= 'Adding new Product with Identity:'.$identity[0].' ';
					
					$menus = $siteAdmin->getProductMenuArray(SITE_ID);
					$parent = self::findCreateImportSection($root, $sections, $menus, $siteAdmin);
					
					if($parent > 0)
					{ 
						$operation = 1; 
						$product = $shopCom->addProduct($title, $parent, $identity[0]);
						$output .= 'to section with id:'.$parent.'<br />';
					} //Add Product To Section
				}
				
				if(($product) && ($product['id'] > 0))
				{
					$sqlupdate = '';
					$updates = self::createFieldUpdateQuerry($exe, $eFields, $row, $product, $cats, $groups, $providers, $brands, $shopCom, $shopCat, $shopProv);
					if($updates)
					{
						foreach($updates as $update)
						{ $result = mysql_query($update); }
						$output .= ' setting product values for:'.$identity[0].'<br />';
					}
				}
			}
			return $output;
		}
	}
	
	function getSqlToPhpDateTime($time)
	{
		if($time)
		{
			$yr = substr($time,0,4);
			$mn = substr($time,5,2);
			$dy = substr($time,8,2);
			
			$ntime = mktime(0,0,0,$mn,$dy,$yr);
			return $ntime;
		}
	}
	
	function getImprtToPhpDateTime($time, $format='', $dy=0, $mn=0, $yr=0)
	{
		if($time != '')
		{
			$make = false;
			if($format != '')
			{
				$format = strtolower($format);
				$yr_s = stripos($format,"yyyy");
				if(is_numeric($yr_s))
				{ $yr_l = 4; }
				else
				{
					$yr_s = stripos($format,'yy');
					if(is_numeric($yr_s))
					{ $yr_l = 2; }
				}
				$mn_s = stripos($format,'mm');
				$dy_s = stripos($format,'dd');
			}
			
			if(is_numeric($yr_s))
			{ 
				$yv = substr($time,$yr_s,$yr_l);
				if(is_numeric($yv))
				{
					if($yv > 1000)
					{ 
						$yr = $yv; 
						$make = true;
					}
				}
				
			}
			
			if(is_numeric($mn_s))
			{ 
				$mv = substr($time,$mn_s,2); 
				if(is_numeric($mv))
				{
					if(($mv > 0) && ($mv < 13))
					{ 
						$mn = $mv; 
						$make = true;
					}
				}
			}
			
			if(is_numeric($dy_s))
			{ 
				$dv = substr($time,$dy_s,2); 
				if(is_numeric($dv))
				{
					if(($dv > 0) && ($dv < 32))
					{ 
						$dy = $dv; 
						$make = true;
					}
				}
			}
			if($make)	
			{ 
				$ntime = mktime(0,0,0,$mn,$dy,$yr); 
				return $ntime;
			}
		}
	}
	
	function createFieldUpdateQuerry($exe, $eFields, $row, $product, &$cats, &$groups, &$providers, &$brands, $shopCom, $shopCat, $shopProv)
	{
		if(($exe) && ($eFields) && ($row) && ($product))
		{
			$i = 0;
			$v = 0;
			
			foreach($eFields as $field)
			{
				if($field['to_table'] == 'product')
				{
					switch ($field['to_field'])
					{
						case 'intro': case 'details': 
							if($row[$field['from_field_no']] != '')
							{
								if(strtolower(trim($product[$field['to_field']])) != strtolower(trim($row[$field['from_field_no']])))
								{	
									if($sql[$field['to_table']] != '')
									{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`="'.$row[$field['from_field_no']].'"'; }
									else
									{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`="'.$row[$field['from_field_no']].'"'; $i++; }
								}
							}
						break;  
						case 'title': case 'stock_unit': case 'weight_unit': case 'dim_unit': 
							if(strtolower(trim($product[$field['to_field']])) != strtolower(trim($row[$field['from_field_no']])))
							{	
								if(!(($field['to_field'] == 'title') && ($row[$field['from_field_no']] == '')))
								{
									if($sql[$field['to_table']] != '')
									{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`="'.$row[$field['from_field_no']].'"'; }
									else
									{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`="'.$row[$field['from_field_no']].'"'; $i++; }
								}
							}
						break;  
						case 'active_start': case 'active_end':
							if($product[$field['to_field']] != $row[$field['from_field_no']])
							{	
								if($row[$field['from_field_no']] != '')
								{
									$pval  	= self::getSqlToPhpDateTime($product[$field['to_field']]);
									$value 	= self::getImprtToPhpDateTime($row[$field['from_field_no']], $field['default_value']);
									
									if($value != $pval)
									{	
										$datval = date("Y-m-d H:i:s", $value);
										if($sql[$field['to_table']] != '')
										{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`="'.$datval.'"'; }
										else
										{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`="'.$datval.'"'; $i++; }
									}
								}
							}
						break; 
						case 'active':
							if($product[$field['to_field']] != $row[$field['from_field_no']])
							{	
								if(is_numeric($row[$field['from_field_no']]))
								{
									if($row[$field['from_field_no']] > 0)
									{ $value = 1; }
									else
									{ $value = 0; }
									
									if($sql[$field['to_table']] != '')
									{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`='.$value; }
									else
									{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`='.$value; $i++; }
								}
							}
						break; 
						case 'views':
							if($product[$field['to_field']] != $row[$field['from_field_no']])
							{	
								if(is_numeric($row[$field['from_field_no']]))
								{
									if($row[$field['from_field_no']] > 0)
									{ $value = $row[$field['from_field_no']]; }
									else
									{ $value = 0; }
									
									if($sql[$field['to_table']] != '')
									{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`='.$value; }
									else
									{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`='.$value; $i++; }
								}
							}
						break; 
						case 'cat_id':
							if($row[$field['from_field_no']] != '')
							{
								$cid = 0;
								$cid = self::findCreateCat($cats, $row[$field['from_field_no']]);
								if(($cid > 0) && ($cid != $product['cat_id']))
								{
									if($sql[$field['to_table']] != '')
									{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`='.$cid; }
									else
									{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`='.$cid; $i++; }
								}
							}
						break;
						case 'group_id':
							if($row[$field['from_field_no']] != '')
							{
								$gid = 0;
								$gid = self::findCreateGroup($groups, $row[$field['from_field_no']], $shopCom);
								if(($gid > 0) && ($gid != $product['group_id']))
								{
									if($sql[$field['to_table']] != '')
									{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`='.$gid; }
									else
									{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`='.$gid; $i++; }
								}
							}
						break;
						case 'provider':
							if($row[$field['from_field_no']] != '')
							{
								$pid = 0;
								$pid = self::findCreateProvider($providers, $row[$field['from_field_no']], $shopProv);
								if(($pid > 0) && ($pid != $product['provider']))
								{
									if($sql[$field['to_table']] != '')
									{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`='.$pid; }
									else
									{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`='.$pid; $i++; }
								}
							}
						break;
						case 'brand':
							if($row[$field['from_field_no']] != '')
							{
								$bid = 0;
								$bid = self::findCreateBrand($brands, $row[$field['from_field_no']], $shopCom);
								if(($bid > 0) && ($bid != $product['brand']))
								{
									if($sql[$field['to_table']] != '')
									{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`='.$bid; }
									else
									{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`='.$bid; $i++; }
								}
							}
						break;
					}
				}
				
				if($field['to_table'] == 'product_vars')
				{
					switch ($field['to_field'])
					{
						case 'var_title': case 'identity': case 'ext_identity': case 'stock_add_txt':
							if($product[$field['to_field']] != $row[$field['from_field_no']])
							{
								$row[$field['from_field_no']] = stripNonAlphaNum($row[$field['from_field_no']]);
								if($sql[$field['to_table']] != '')
								{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`="'.$row[$field['from_field_no']].'"'; }
								else
								{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`="'.$row[$field['from_field_no']].'"'; $i++; }
							}
						break;  
						case 'buy_min': case 'stock_count': case 'stock_add_quan': case 'net_weight': case 'net_weight': case 'gros_weight':
						case 'length': case 'width': case 'height': case 'length':
							if($product[$field['to_field']] != $row[$field['from_field_no']])
							{
								$row[$field['from_field_no']] = stripNonAlphaNum($row[$field['from_field_no']]);
								if($sql[$field['to_table']] != '')
								{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`='.$row[$field['from_field_no']]; }
								else
								{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`='.$row[$field['from_field_no']]; $i++; }
							}
						break; 
						case 'std_price': case 'now_price': case 'offer_price':
							if(($product[$field['to_field']] != $row[$field['from_field_no']]) && ($row[$field['from_field_no']] != ''))
							{
								$price = $row[$field['from_field_no']];
								$price = str_ireplace(' ','',$price);
								$price = str_ireplace(',','.',$price);
								
								if($sql[$field['to_table']] != '')
								{ $sql[$field['to_table']] .= ', `'.$field['to_field'].'`='.number_format($price,2,'.','').''; }
								else
								{ $sql[$field['to_table']] .= '`'.$field['to_field'].'`='.number_format($price,2,'.','').''; $i++; }
							}
						break;
					}
				}
				
				if($field['to_table'] == 'product_vals')
				{
					if($row[$field['from_field_no']] != '')
					{
						if($field['to_field'] > 0) // Defined attribute
						{
							$vid = 0;
							$aid = 0;
							if($product['attributes'])
							{
								foreach($product['attributes'] as $attribute)
								{
									if($attribute['id'] == $field['to_field'])
									{ $aid = $attribute['id']; }
								}
							}
							if($aid == 0)
							{ $shopCom->addAttributeToProduct($product['id'], $field['to_field']); }
							
							if($product['vals'])
							{
								foreach($product['vals'] as $val)
								{
									if($val['attribute_id'] == $field['to_field'])
									{ 
										$vid = $val['id'];
										$sql['product_vals'] = ' UPDATE '.DB_PERFIX.'product_vals ';
										$sql['product_vals'] .= ' SET value="'.$row[$field['from_field_no']].'" ';
										$sql['product_vals'] .= ' WHERE id='.$val['id'].'; ';
										mysql_query($sql['product_vals']);
									}
								}
							}
							if($vid == 0)
							{
								$sql['product_vals'] = ' INSERT INTO '.DB_PERFIX.'product_vals (`product_id`, `attribute_id`, `value_id`, `value`) ';
								$sql['product_vals'] .= ' VALUES ('.$product['id'].', '.$field['to_field'].', 0, "'.$row[$field['from_field_no']].'"); ';
								mysql_query($sql['product_vals']);
							}
						}
					}
				}
			}
			
			if($sql)
			{
				$sql['product_vals'] = '';
				if($sql['product'] != '')
				{ $sql['product'] = 'UPDATE `'.DB_PERFIX.'product` SET '.$sql['product'].' WHERE `id`='.$product['id'].';'; }
				if($sql['product_vars'] != '')
				{ 
					$sql['product_vars']  = 'UPDATE `'.DB_PERFIX.'product_vars` SET '.$sql['product_vars'].' ';
					$sql['product_vars'] .= 'WHERE `product_id`='.$product['id'].' AND `identity`="'.$product['identity'].'";'; 
				}
				return $sql;
			}
		}
	}
	
	
	function findCreateImportSection($root=0, $sections, &$menus, $siteAdmin)
	{
		if($sections)
		{
			if(count($sections) > 0)
			{
				$i=1;
				$j=0;
				$start = 0;
				$parent = 0;
				foreach($sections as $section)
				{
					if($menus[$section])
					{ 
						foreach($menus[$section] as $menuitem)
						{
							if($root > 0)
							{ 
								if($i == 1)
								{
									if($menuitem['parent_id'] == $root)
									{ 
										$path[$i] 	= $menuitem['id']; 
										$parent 	= $menuitem['id']; 
										$start 		= $i;
									}
								}
								else
								{
									if($menuitem['parent_id'] == $parent)
									{ 
										$path[$i] 	= $menuitem['id']; 
										$parent 	= $menuitem['id']; 
										$start 		= $i;
									}
								}
							}
							$j++;
						}
					}
					$i++;
				}
			}
			
			if($path)
			{
				if(count($path) == count($sections))
				{ $parent = $path[$start]; }
				else
				{
					for($i=($start+1); $i<=count($sections); $i++)
					{ $parent = $siteAdmin->addMenuItem($parent, $sections[$i], 6, SITE_ID); }
				}
				return $parent;
			}
		}
	}
	
	function findCreateBrand(&$brands, $ivalue, $shopCom)
	{
		$result = 0;
		foreach($brands as $brand)
		{
			if($brand->getTitleImport() == $ivalue)
			{ $result = $brand['id']; }
		}
		if(($result == 0) && (is_numeric($ivalue)))
		{
			foreach($brands as $brand)
			{
				if($brand['id'] == $ivalue)
				{ $result = $brand['id']; }
			}
		}
		if($result == 0)
		{
			foreach($brands as $brand)
			{
				if(strtolower($brand['title']) == strtolower($ivalue))
				{ $result = $brand['id']; }
			}
		}
		if($result == 0)
		{
			$brands[(count($brands)+1)] = $shopCom->addShopBrand($ivalue, $ivalue);
			$result = $brands[(count($brands))]['id'];
		}
		return $result;
	}
	
	function findCreateProvider(&$providers, $ivalue, $shopProv)
	{
		$result = 0;
		foreach($providers as $provider)
		{
			if($provider->getTitleImport() == $ivalue)
			{ $result = $provider['id']; }
		}
		if(($result == 0) && (is_numeric($ivalue)))
		{
			foreach($providers as $provider)
			{
				if($provider['id'] == $ivalue)
				{ $result = $provider['id']; }
			}
		}
		if($result == 0)
		{
			foreach($providers as $provider)
			{
				if(strtolower($provider['title']) == strtolower($ivalue))
				{ $result = $provider['id']; }
			}
		}
		if($result == 0)
		{
			$providers[(count($providers)+1)] = $shopProv->addShopProvider($ivalue, $ivalue);
			$result = $providers[(count($providers))]['id'];
		}
		return $result;
	}
	
	function findCreateCat(&$cats, $ivalue)
	{
		global $shopCom;
		global $shop;
		
		$result = 0;
		
		$cats = $shop->getCats();
		
		foreach($cats as $cat)
		{
			if($cat->getTitleImport() == $ivalue)
			{ $result = $cat['id']; }
		}
		
		if(($result == 0) && (is_numeric($ivalue)))
		{
			foreach($cats as $cat)
			{
				if($cat['id'] == $ivalue)
				{ $result = $cat['id']; }
			}
		}
		
		if($result == 0)
		{
			foreach($cats as $cat)
			{
				if(strtolower($cat['title']) == strtolower($ivalue))
				{ $result = $cat['id']; }
			}
		}
		
		if($result == 0)
		{
			$cats[(count($cats)+1)] = $shopCom->addShopCat($ivalue, $ivalue);
			$result = $cats[(count($cats))]['id'];
		}
		return $result;
	}
	
	function findCreateGroup(&$groups, $ivalue, $shopCom)
	{
		$result = 0;
		foreach($groups as $group)
		{
			if($group->getTitleImport() == $ivalue)
			{ $result = $group['id']; }
		}
		if(($result == 0) && (is_numeric($ivalue)))
		{
			foreach($groups as $group)
			{
				if($group['id'] == $ivalue)
				{ $result = $group['id']; }
			}
		}
		if($result == 0)
		{
			foreach($groups as $group)
			{
				if(strtolower($group['title']) == strtolower($ivalue))
				{ $result = $group['id']; }
			}
		}
		if($result == 0)
		{
			$groups[(count($groups)+1)] = $shopCom->addProductGroup($ivalue, $ivalue);
			$result = $groups[(count($groups))]['id'];
		}
		return $result;
	}
	
	function runImageImport($exe, $shopCom, $thumb)
	{	
		if($exe['type'] == 1)
		{	
			if(is_dir(PRODUCT_PATH.'import/'.$exe['src_loc']))
			{
				$path = PRODUCT_PATH.'import/'.$exe['src_loc'];
				if(!(is_dir($path.'complete/')))
				{ mkdir($path.'complete/'); }
				
				$output = '<br />Scaning directory:'.$path;
				
				$files = scandir($path);
				if($files)
				{
					set_time_limit(count($files)+60);
					$output = '<br />Found:'.(count($files)-2).' files';
					$i = 1;
					$extList = getValidImgExt();
					$where = '';
					foreach($files as $file)
					{
						$info = pathinfo($path.'/'.$file);
						if($extList[$info['extension']] != '')
						{
							if($i > 1)
							{ $where 	.= ' OR v.identity="'.$info['filename'].'" '; }
							else
							{ $where 	.= ' v.identity="'.$info['filename'].'" '; }
							$i++;
						}
					}
					if($where != '')
					{
						$output .= '<br />Found:valid files';
						
						$sql  = 'SELECT p.id, p.has_image, v.id as variation_id, v.identity FROM '.DB_PERFIX.'product AS p  ';
						$sql .= 'LEFT JOIN '.DB_PERFIX.'product_vars AS v ON p.id=v.product_id ';
						$sql .= 'WHERE '.$where.';';
						echo $sql;
						$output .= '<br />Searching for products with matching identity';
						$result = mysql_query($sql);
						if(mysql_num_rows($result) > 0)
						{
							$i = 0;
							while($row = mysql_fetch_array($result))
							{ 
								foreach(array_keys($row) as $key)
								{ $items[$i][$key] = $row[$key]; }
								if($items[$i]['id'] > 0)
								{
									$items[$i]['images'] = $shopCom->getProductImages($item['id']);
								}
								$i++;
							}
						}
						
						if($items)
						{
							$output .= '<br />Found '.count($items).' products with matching identity';
							foreach($items as $item)
							{
								if(!$item['images'])
								{
									foreach($files as $file)
									{
										$info = pathinfo($path.'/'.$file);
										if(($extList[$info['extension']] != '') && ($info['extension'] == 'jpg'))
										{
											if($info['filename'] == $item['identity'])
											{
												$result = copyAsProductImage($path.$file, $item['id'], $info['filename'], 0, $extList[$info['extension']], $thumb);
												if($result == 1)
												{ 
													$output .= '<br />Image '.$file.' added to product with id:'.$item['id'];
													if(!(stripos($path,'complete') > 0)) 
													{
														if(copy($path.$file, $path.'complete/'.$file))
														{ unlink($path.$file); } 
														$output .= '<br />Image '.$file.' copied to:'.$path.'complete/'.$file;
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
				return $output;
			}
		}
	}
}

class ShopExeImpField extends Validator
{
	private $fieldNo;
	private $fieldTitle;
	private $toTable;
	private $toField;
	private $emptyAction;
	private $defVal;
	private $perfix;
	private $postfix;
	
	public function ShopExeImpField() {} 
	     
	/* GET FUNCTIONS */
	public function getFieldNo() { return $this->fieldNo; } 
	public function getFieldTitle() { return $this->fieldTitle; }
	public function getToTable() { return $this->toTable; }
	public function getToField() { return $this->toField; }
	public function getEmptyAction() { return $this->emptyAction; }
	public function getDefVal() { return $this->defVal; }
	public function getPerfix() { return $this->perfix; }
	public function getPostfix() { return $this->postfix; }
	
	/* SET FUNCTIONS */
	public function setFieldNo($fieldNo) 
	{ $this->fieldNo = $fieldNo; } 
	
	public function setFieldTitle($fieldTitle) 
	{ $this->fieldTitle = parent::strip_html(trim($fieldTitle)); } 
	
	public function setToTable($toTable) 
	{ $this->toTable = parent::strip_html(trim($toTable)); }
	
	public function setToField($toField) 
	{ $this->toField = parent::strip_html(trim($toField)); } 
	
	public function setEmptyAction($emptyAction) 
	{ $this->emptyAction = $emptyAction; } 

	public function setDefVal($defVal) 
	{ $this->defVal = trim($defVal); } 
	
	public function setPerfix($perfix) 
	{ $this->perfix = trim($perfix); }
	
	public function setPostfix($postfix) 
	{ $this->postfix = trim($postfix); }
	
	public function addField($parent)
	{
		if($parent > 0)
		{
			$insert  = 'INSERT INTO '.DB_PERFIX.'shop_exe_fields (`parent_id`, `from_field_no`, `from_field_title`)'; 
			$insert .= 'VALUES ('.$parent.', '.$this->fieldNo.', "'.$this->fieldTitle.'");';
			$result = mysql_query($insert);
		}
	}
	
	public function saveField($id, $old)
	{
		if($id > 0)
		{
			if(
				($old['from_field_no'] != $this->fieldNo) ||
				($old['from_field_title'] != $this->fieldTitle) ||
				($old['to_table'] != $this->toTable) ||
				(($old['if_empty_action'] != $this->emptyAction) && ($this->emptyAction != '')) ||
				($old['default_value'] != $this->defVal) ||
				($old['perfix'] != $this->perfix) ||
				($old['postfix'] != $this->postfix) ||
				($old['default_value'] != $this->defVal) ||
				($old['to_field'] != $this->toField)
			  )
			{
				
				$update  = 'UPDATE '.DB_PERFIX.'shop_exe_fields SET ';
				$update .= 'from_field_no='.$this->fieldNo.', ';
				$update .= 'from_field_title="'.$this->fieldTitle.'", ';
				$update .= 'to_table="'.$this->toTable.'", ';
				$update .= 'to_field="'.$this->toField.'", ';
				if($this->emptyAction != '')
				{ $update .= 'if_empty_action='.$this->emptyAction.', '; }
				$update .= 'postfix="'.$this->postfix.'", ';
				$update .= 'perfix="'.$this->perfix.'", ';
				$update .= 'default_value="'.$this->defVal.'" ';
				$update .= 'WHERE id='.$id.' LIMIT 1;';
				$update = mysql_query($update);
			}
		}
	}
	
	public function getFields($parent)
	{
		if($parent > 0)
		{
			$select = 'SELECT * FROM '.DB_PERFIX.'shop_exe_fields WHERE parent_id='.$parent.' ORDER BY from_field_no ASC;';
			$result = mysql_query($select);
			if(mysql_num_rows($result) > 0)
			{
				$i=0;
				while($row = mysql_fetch_array($result))
				{
					foreach(array_keys($row) as $key)
					{ $item[$i][$key] = $row[$key]; }
					$i++;
				}
				return $item;
			}
		}
	}
}


function getFolders($path)
{
	$files = scandir($path);
	if($files)
	{
		foreach($files as $file)
		{
			if(($file != '.') && ($file != '..'))
			{
				if(is_dir($path.$file))
				{
					$folders[$file] = $file;
				}
			}
		}
	}
	return $folders;
}
function getFolderOptions($selected, $parent='', $lev=0)
{
	$output = '';
	$folders = getFolders(PRODUCT_PATH.'import/'.$parent);
	if($folders)
	{
		foreach($folders as $folder)
		{
			$path = $parent.$folder.'/' ;
			
			$output .= '<option value="'.$path.'" '.getIsSelectedHTML($selected, $path).'>/';
			$output .= $path.' ('.(count(scandir(PRODUCT_PATH.'import/'.$path))-2).' files)</option>';

			$output .= getFolderOptions($selected, $path);
		}
	}
	return $output;
}

function getImagesInFolder($path)
{
	$files = scandir($path);
	if($files)
	{
		foreach($files as $file)
		{
			if(!(is_dir($path.$file)))
			{
				echo $file.'<br>';
			}
		}
	}
}

function getexefields($table='')
{
	global $words;
	global $attributes;
	
	if($table == 'product_vals')
	{
		$i=0;
		$eFields[$i]['title'] = ucfirst($txt->getWord('new')).' '.$txt->getWord('attribute'); 
		$eFields[$i]['value'] = '-1';
		$i++;
		
		foreach($attributes as $attribute)
		{
			if($attribute['effect'] == 0)
			{
				$eFields[$i]['title'] = $attribute['title'];
				$eFields[$i]['value'] = $attribute['id'];
				$i++;
			}
		}
		return $eFields;
	}
	
	if($table == 'product_var_vals')
	{
		$i=0;
		foreach($attributes as $attribute)
		{
			if($attribute['effect'] == 1)
			{
				$eFields[$i]['title'] = $attribute['title'];
				$eFields[$i]['value'] = $attribute['id'];
				$i++;
			}
		}
		return $eFields;
	}
	
	if($table == 'menu')
	{
		for($i=0; $i<7; $i++)
		{
			$eFields[$i]['title'] = 'Level '.$i;
			$eFields[$i]['value'] = $i;
		}
		return $eFields;
	}
	
	if($table == 'product')
	{
		$i=0;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('title')); 
		$eFields[$i]['value'] = 'title';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('category'));
		$eFields[$i]['value'] = 'cat_id';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('productgroup'));
		$eFields[$i]['value'] = 'group_id';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('brand'));
		$eFields[$i]['value'] = 'brand';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('provider'));
		$eFields[$i]['value'] = 'provider';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('stock')).' '.ucfirst($txt->getWord('unit'));
		$eFields[$i]['value'] = 'stock_unit';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('weight')).' '.ucfirst($txt->getWord('unit'));
		$eFields[$i]['value'] = 'weight_unit';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('dimunit'));
		$eFields[$i]['value'] = 'dim_unit';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('intro'));
		$eFields[$i]['value'] = 'intro';
		$eFields[$i]['type']  = 'html';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('details'));
		$eFields[$i]['value'] = 'details';
		$eFields[$i]['type']  = 'html';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('activation')).' YYYY-MM-DD';
		$eFields[$i]['value'] = 'active_start';
		$eFields[$i]['type']  = 'datetime';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('deactivation')).' YYYY-MM-DD';
		$eFields[$i]['value'] = 'active_end';
		$eFields[$i]['type']  = 'datetime';
		$i++;
		
		return $eFields;
	}
	
	if($table == 'product_vars')
	{
		$i=0;
		$eFields[$i]['title'] = ucfirst($txt->getWord('description')); 
		$eFields[$i]['value'] = 'var_title';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('identity')); 
		$eFields[$i]['value'] = 'identity';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('identity')).' '.ucfirst($txt->getWord('part')).' 1'; 
		$eFields[$i]['value'] = 'identity_1';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('identity')).' '.ucfirst($txt->getWord('part')).' 2'; 
		$eFields[$i]['value'] = 'identity_2';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('identity')).' '.ucfirst($txt->getWord('part')).' 3'; 
		$eFields[$i]['value'] = 'identity_3';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('ext_identity')); 
		$eFields[$i]['value'] = 'ext_identity';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('buy_min')); 
		$eFields[$i]['value'] = 'buy_min';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('stock')).' '.ucfirst($txt->getWord('count')); 
		$eFields[$i]['value'] = 'stock_count';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('stock')).' '.ucfirst($txt->getWord('date')); 
		$eFields[$i]['value'] = 'stock_add_date';
		$eFields[$i]['type']  = 'date';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('stock')).' '.ucfirst($txt->getWord('date')).' '.ucfirst($txt->getWord('add')).' #'; 
		$eFields[$i]['value'] = 'stock_add_quan';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('stock')).' txt'; 
		$eFields[$i]['value'] = 'stock_add_txt';
		$eFields[$i]['type']  = 'txt';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('net_weight')); 
		$eFields[$i]['value'] = 'net_weight';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('gros_weight')); 
		$eFields[$i]['value'] = 'gros_weight';
		$eFields[$i]['type']  = 'int';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('length')); 
		$eFields[$i]['value'] = 'length';
		$eFields[$i]['type']  = 'int';
		$i++;
		 	
		$eFields[$i]['title'] = ucfirst($txt->getWord('width')); 
		$eFields[$i]['value'] = 'width';
		$eFields[$i]['type']  = 'int';
		$i++;
	
		$eFields[$i]['title'] = ucfirst($txt->getWord('height')); 
		$eFields[$i]['value'] = 'height';
		$eFields[$i]['type']  = 'int';
		$i++;
		 	
		$eFields[$i]['title'] = ucfirst($txt->getWord('std_price')); 
		$eFields[$i]['value'] = 'std_price';
		$eFields[$i]['type']  = 'dbl';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('now_price')); 
		$eFields[$i]['value'] = 'now_price';
		$eFields[$i]['type']  = 'dbl';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('offer')).' '.ucfirst($txt->getWord('price')); 
		$eFields[$i]['value'] = 'offer_price';
		$eFields[$i]['type']  = 'dbl';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('offer')).' '.ucfirst($txt->getWord('start')); 
		$eFields[$i]['value'] = 'offer_start';
		$eFields[$i]['type']  = 'datetime';
		$i++;
		
		$eFields[$i]['title'] = ucfirst($txt->getWord('offer')).' '.ucfirst($txt->getWord('end')); 
		$eFields[$i]['value'] = 'offer_end';
		$eFields[$i]['type']  = 'datetime';
		$i++;	
		
		return $eFields;
	}
}

function getExeDefaultValueOptions($table='', $field='', $val)
{
	global $words;
	$select_top = '<select class="small-m" name="default_value[]" onchange="submit();">';
	$select_bot = '</select>';
	$def_inp = '<input type="text" class="small-m" name="default_value[]" value="'.$val.'">';
	
	$output = '';
	$maxlen = 100;
	
	switch ($table)
	{
		case 'product':
			switch ($field)
			{
				case 'cat_id':
					global $cats;
					$output  = $select_top;
						$output .= '<option value="0">'.ucfirst($txt->getWord('category')).' '.ucfirst($txt->getWord('undefined')).'</option>';
						if($cats)
						{
							foreach($cats as $cat)
							{ $output .= '<option value="'.$cat['id'].'" '.getIsSelectedHTML($cat['id'], $val).'>'.$cat['title'].'</option>'; }
						}
					$output .= $select_bot;
				break;
				case 'group_id':
					global $groups;
					$output  = $select_top;
						$output .= '<option value="0">'.ucfirst($txt->getWord('group')).' '.ucfirst($txt->getWord('undefined')).'</option>';
						if($groups)
						{
							foreach($groups as $group)
							{ $output .= '<option value="'.$group['id'].'" '.getIsSelectedHTML($group['id'], $item['group_id']).'>'.$group['title'].'</option>'; }
						}
					$output .= $select_bot;
				break;
				case 'brand':
					global $brands;
					$output  = $select_top;
						$output .= '<option value="0">'.ucfirst($txt->getWord('brand')).' '.ucfirst($txt->getWord('undefined')).'</option>';
						if($brands)
						{
							foreach($brands as $brand)
							{ $output .= '<option value="'.$brand['id'].'" '.getIsSelectedHTML($brand['id'], $item['brand']).'>'.$brand['title'].'</option>'; }
						}
					$output .= $select_bot;
				break;
				case 'provider':
					global $providers;
					$output  = $select_top;
						$output .= '<option value="0">'.ucfirst($txt->getWord('provider')).' '.ucfirst($txt->getWord('undefined')).'</option>';
						if($providers)
						{
							foreach($providers as $provider)
							{ $output .= '<option value="'.$provider['id'].'" '.getIsSelectedHTML($provider['id'], $item['provider']).'>'.$provider['title'].'</option>'; }
						}
					$output .= $select_bot;
				break;
			}
		break;
		
		case 'product_vars':
			switch ($field)
			{
				case (($field == 'net_weight') || ($field == 'gros_weight') || ($field == 'length') || ($field == 'width')):
					$maxlen = 9;
				break;
				case (($field == 'std_price') || ($field == 'now_price') || ($field == 'offer_price')):
					$maxlen = 14;
				break;
				case (($field == 'offer_start') || ($field == 'offer_end')):
					if($val != '')
					{ $output = '<input type="text" maxlength="20" class="mall-m" name="default_value[]" value="'.$val.'">'; }
					else
					{ $output = '<input type="text" maxlength="20" class="mall-m" name="default_value[]" value="0000-00-00 00:00:00">'; }
				break;
			}
		break;
		
		case 'product_vals':
			global $attributes;
			foreach($attributes as $attribute)
			{
				if(($attribute['effect'] == 0) && ($attribute['id'] == $field))
				{
					if($attribute['predefined'] > 0)
					{ 
						$ShopAtt = new ShopAttribute();
						$attribute['values'] = $ShopAtt->getShopAttributeValues($attribute['id']); 
						if($attribute['values'])
						{
							$output  = $select_top;
							$output .= '<option value="0" '.getIsSelectedHTML(0, $val).'>'.ucfirst($txt->getWord('undefined')).'</option>';
							foreach($attribute['values'] as $value)
							{ $output .= '<option value="'.$value['id'].'" '.getIsSelectedHTML($value['id'], $val).'>'.$value['value'].'</option>'; }
							$output .= $select_bot;
						}
					}
				}
			}
		break;
		
		case 'product_var_vals':
			global $attributes;
			foreach($attributes as $attribute)
			{
				if(($attribute['effect'] == 1) && ($attribute['id'] == $field))
				{
					if($attribute['predefined'] > 0)
					{ 
						$ShopAtt = new ShopAttribute();
						$attribute['values'] = $ShopAtt->getShopAttributeValues($attribute['id']); 
						if($attribute['values'])
						{
							$output  = $select_top;
							$output .= '<option value="0" '.getIsSelectedHTML(0, $val).'>'.ucfirst($txt->getWord('undefined')).'</option>';
							foreach($attribute['values'] as $value)
							{ $output .= '<option value="'.$value['id'].'" '.getIsSelectedHTML($value['id'], $val).'>'.$value['value'].'</option>'; }
							$output .= $select_bot;
						}
					}
				}
			}
		break;
	}
	if($output == '')
	{ $output = '<input type="text" class="small-m" maxlength="'.$maxlen.'" name="default_value[]" value="'.$val.'">'; }
	return $output;
}
?>